//
//  YLTitleChoiceTag.m
//  YLFinanceService
//
//  Created by she1323 on 2017/8/24.
//  Copyright © 2017年 she1323. All rights reserved.
//

#import "YLTitleChoiceTag.h"
#import "YLGlobeHeader.h"
#import <Masonry.h>
@interface YLTitleChoiceTag ()
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, weak) UIButton *lastButton;
@property (nonatomic, weak) UIButton *firstButton;
@property (nonatomic, weak) UIView *line;
@end

@implementation YLTitleChoiceTag


- (instancetype)initWithTitle:(NSArray<NSString *> *)titles
{
    if (self = [super initWithFrame:CGRectZero]) {
        self.titles = titles;
    }
    return self;
}

- (void)setTitles:(NSArray *)titles
{
    _titles = titles;
    __weak typeof(self) weakSelf = self;
    CGFloat buttonWidth = YLScreenW / (titles.count);

    for (NSInteger i = 0; i < titles.count; i ++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitleColor:YLLineColor forState:UIControlStateNormal];
        [button setTitleColor:YLMainColor forState:UIControlStateSelected];
        [button setTitle:titles[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        _lastButton = button;
        button.tag = i;
        if (i == 0) {
            _firstButton = button;
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.left.mas_equalTo(weakSelf);
                make.bottom.mas_equalTo(weakSelf).mas_offset(-1);
                make.width.mas_equalTo(buttonWidth);
            }];
        } else {
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(weakSelf.mas_centerX);
                make.top.bottom.mas_equalTo(weakSelf);
                make.width.mas_equalTo(buttonWidth);
            }];
        }
    }
//
    UIView *line = [[UIView alloc] init];
    _line = line;
    [self addSubview:line];
    line.backgroundColor = YLMainColor;
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(buttonWidth - 30);
        make.bottom.mas_equalTo(weakSelf);
        make.height.mas_equalTo(1);
        make.centerX.mas_equalTo(weakSelf.firstButton);
    }];
    
    UIView * lightGrayline = [[UIView alloc] init];
    [self addSubview:lightGrayline];
    [lightGrayline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(weakSelf);
        make.height.mas_equalTo(1);
    }];
    
    
}

- (void)btnClick:(UIButton *)button
{
    UIButton *selectedButton = self.subviews[button.tag];
    [_line mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(selectedButton.mas_centerX);
    }];
    
}

@end
